package com.xiangban.xiangbanmall.controller;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.xiangban.xiangbanmall.service.PayService;
import com.xiangban.xiangbanmall.service.UserMemberService;
import com.xiangban.xiangbanmall.utils.WXConfigUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @Author Mr. MaYaYun
 * @Data 2021/11/13 11:00
 */
@RestController
@RequestMapping("/api/mall/pay")
@Api(tags = "微信支付")
public class PayController {
    protected final static Logger logger = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private PayService payService;
    @Autowired
    private UserMemberService userMemberService;



    @RequestMapping(value = "/wxPayNotify")
    @ResponseBody
    public String wxPayNotify(HttpServletRequest request) {
        logger.info("进入回调");
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            // 将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml = sb.toString();
            String result = payService.payBack(resXml);
            WXConfigUtil config = new WXConfigUtil();
            WXPay wxpay = new WXPay(config);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(resXml);
            // 调用官方SDK转换成map类型数据
//            if (wxpay.isResponseSignatureValid(notifyMap)) {
            if (true) {
                // 验证签名是否有效
                String return_code = notifyMap.get("return_code");// 状态
                String out_trade_no = notifyMap.get("out_trade_no");// 商户订单号
                String attach = notifyMap.get("attach");// 自定义参数
                if (return_code.equals("SUCCESS")) {
                    if (out_trade_no != null) {
                        logger.info("===================回调成功===========");
                        //#业务逻辑处理
                        userMemberService.businessProcessing(out_trade_no,attach);
                        logger.info(JSON.toJSONString(notifyMap));
                        logger.info("=======成功返回报文========"+JSON.toJSONString(result));
                    }
                }
            }
            return result;

        } catch (Exception e) {
            logger.error("微信回调接口失败 error : {}", e);
            e.printStackTrace();
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            logger.error(result);
            return result;
        }
    }
}
